package com.bjpowernode.singleton.attack;

import java.io.*;

/**
 * @ClassName Singleton03
 *
 * @Author Cat
 */
public final class SingletonAttack03 implements Serializable {

    private static SingletonAttack03 instance = null;

    private static boolean flag = true;

    private SingletonAttack03() {
        /*if (instance != null) {
            throw new RuntimeException("不要反射攻击.");
        }*/
        if (flag) {
            flag = false;
        } else {
            throw new RuntimeException("反射攻击..");
        }
    }

    public static synchronized SingletonAttack03 getInstance() {
        if (null == instance) {
            instance = new SingletonAttack03();
        }
        return instance;
    }

    public Object readResolve() {
        return instance;
    }

    public static void main(String[] args) throws Exception{
        //SingletonAttack02 instance1 = SingletonAttack02.getInstance();
        //System.out.println(instance1);

        /*Constructor<SingletonAttack03> constructor = SingletonAttack03.class.getDeclaredConstructor();
        constructor.setAccessible(true);//对私有构造器开放权限

        SingletonAttack03 newInstance1 = constructor.newInstance();
        System.out.println(newInstance1);

        SingletonAttack03 newInstance2 = constructor.newInstance();
        System.out.println(newInstance2);

        SingletonAttack03 newInstance3 = constructor.newInstance();
        System.out.println(newInstance3);*/

        //序列化
        SingletonAttack03 instance1 = SingletonAttack03.getInstance();
        System.out.println(instance1);

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("SerSingleton.obj"));
        oos.writeObject(instance1);
        oos.flush();
        oos.close();

        //反序列化
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("SerSingleton.obj"));
        SingletonAttack03 rs01 = (SingletonAttack03)ois.readObject();
        ois.close();
        System.out.println(rs01);
    }
}